﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.ReadAPI.Applications.Commands.Roles;
using B.S.Meeting.ReadAPI.Applications.Commands.Users;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.Meeting.ReadAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        IMediator mediator;
        ILogger<UserController> logger;

        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userPhone">手机号</param>
        /// <param name="userPwd">密码</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous] // 允许匿名访问
        public async Task<APIResult<UserDto>> Login([FromQuery]string? userName, string? userPhone, string userPwd)
        {
            try
            {
                LoginCommand cmd = new LoginCommand
                {
                    UserName = userName,
                    UserPhone = userPhone,
                    UserPwd = userPwd
                };
                logger.LogInformation($"用户：{userName},用户手机号：{userPhone}，在{DateTime.Now}登录成功!");
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("登录出错", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<List<UserDto>>>> GetUser([FromQuery]GetUserCommand cmd)
        {
            try
            {
                var result=await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "获取用户列表失败");
                throw;
            }
        }

        /// <summary>
        /// 下拉框获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<IList<Role>>> SelectRole()
        {

           try
            {
                SelectRoleCommand cmd=new SelectRoleCommand();
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "获取角色列表失败");
                throw;
            }
        }
    }
}
